package com.fjzx.androidframe.ui.flow;

import android.view.View;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xiongyongcong
 */
public abstract class TagAdapter<T> {
    private List<T> mTagDatas;
    private OnDataChangedListener mOnDataChangedListener;
    private HashSet<Integer> mCheckedPosList = new HashSet<>();

    public TagAdapter(List<T> datas) {
        mTagDatas = datas;
    }

    public TagAdapter() {
        mTagDatas = new ArrayList<>();
    }

    public void setSelectedList(int... poses) {
        Set<Integer> set = new HashSet<>();
        for (int pos : poses) {
            set.add(pos);
        }
        setSelectedList(set);
    }

    public void submitList(List<T> datas) {
        if (mTagDatas == null) {
            mTagDatas = new ArrayList<>();
        }
        mTagDatas.clear();
        mTagDatas.addAll(datas);
        notifyDataChanged();
    }

    public void setSelectedList(Set<Integer> set) {
        mCheckedPosList.clear();
        if (set != null) {
            mCheckedPosList.addAll(set);
        }
        notifyDataChanged();
    }

    public List<T> getSelectedDataList() {
        if (mCheckedPosList == null || mCheckedPosList.isEmpty()) {
            return null;
        }
        List<T> data = new ArrayList<>();
        for (Integer position : mCheckedPosList) {
            data.add(mTagDatas.get(position));
        }
        return data;
    }

    public void clearSelected() {
        mCheckedPosList.clear();
        notifyDataChanged();
    }

    HashSet<Integer> getPreCheckedList() {
        return mCheckedPosList;
    }

    public int getCount() {
        return mTagDatas == null ? 0 : mTagDatas.size();
    }

    public T getItem(int position) {
        return mTagDatas == null ? null : mTagDatas.get(position);
    }

    public abstract View getView(FlowLayout parent, int position, T t);

    public void onSelected(int position, View view) {
        if (!mCheckedPosList.contains(position)) {
            mCheckedPosList.add(position);
        }
    }

    public void unSelected(int position, View view) {
        if (mCheckedPosList.contains(position)) {
            mCheckedPosList.remove(position);
        }
    }

    public void setSelected(int position) {
        mCheckedPosList.add(position);
        notifyDataChanged();
    }

    public void notifyDataChanged() {
        if (mOnDataChangedListener != null) {
            mOnDataChangedListener.onChanged();
        }
    }

    interface OnDataChangedListener {
        void onChanged();
    }

    void setOnDataChangedListener(OnDataChangedListener listener) {
        mOnDataChangedListener = listener;
    }
}
